package com.ruoyi.chat.LongConnection.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.chat.LongConnection.model.LongConnectionLoginDTO;
import com.ruoyi.chat.LongConnection.model.ReturnMsgVo;
import com.ruoyi.chat.LongConnection.util.LongConnectionMsgUtil;
import com.ruoyi.chat.LongConnection.util.LongConnectionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @package: com.ruoyi.chat.LongConnection.handler
 * @className: LogHandler
 * @description: 登录handler
 * @author MaTaoxun
 * @date 2021/9/28 23:00
*/
public class LogHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx){
        LongConnectionUtil.removedByChannel((SocketChannel) ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        msg.retain();
        //若该channel已经登陆，则直接略过登录
        if (LongConnectionUtil.checkChannelWhetherOnline((SocketChannel) ctx.channel())){
            ctx.fireChannelRead(msg.text());
            return;
        }
        ObjectMapper mapper = new ObjectMapper();
        LongConnectionLoginDTO loginDTO = null;
        //转换出登录DTO
        try {
            loginDTO = mapper.readValue(msg.text(), LongConnectionLoginDTO.class);
        }catch (Exception e){
            ctx.writeAndFlush(LongConnectionMsgUtil.ObjectToWSTextResult(new ReturnMsgVo(ReturnMsgVo.WONT_LOG,"需要登录,或者登录数据包错误")));
            return;
        }
        //添加连接
        LongConnectionUtil.add(loginDTO.getSenderId(), (SocketChannel)ctx.channel());
        ctx.writeAndFlush(LongConnectionMsgUtil.ObjectToWSTextResult(new ReturnMsgVo(ReturnMsgVo.LOG_SUCCESS,loginDTO.getSenderId()+"成功登录")));
        msg.release();

    }
}
